/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package concurrent.mergesort;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Iaroslav_Mazai
 */
public class ComputationalUnit implements ValueReturningRunnable<List<Object>> {

	List<Object> list;

	public ComputationalUnit(List<Object> list) {
		this.list = list;
	}

	public List<Object> sort(List<Object> list, boolean spawnNewAllowed) {
		if (list.size() <= 1) {
			return list;
		}

		Integer middle = list.size() / 2;
		List<Object> left = new ArrayList<>();
		List<Object> right = new ArrayList<>();
		List<Object> result = new ArrayList<>();

		for (int i = 0; i < middle; i++) {
			left.add(list.get(i));
		}

		for (int i = middle; i < list.size(); i++) {
			right.add(list.get(i));
		}

		if (spawnNewAllowed) {
			ComputationalUnit newUnit = new ComputationalUnit(right);
			Thread thread = new Thread(newUnit);
			thread.start();

			left = sort(left, false);

			try {
				thread.join();
			} catch (InterruptedException ex) {
			}

			right = newUnit.getValue();
		} else {
			left = sort(left, false);
			right = sort(right, true);
		}


		result = MergeSortUtils.merge(left, right);

		return result;
	}

	@Override
	public void run() {
		List<Object> sortedList = sort(list, true);
		list = sortedList;
	}

	@Override
	public List<Object> getValue() {
		return list;
	}
}
